package network;

import java.nio.ByteBuffer;

/**
 * @author Erik
 * Header-container class
 * contains all header info
 */
//approved by RamboErik (!)
public class PackageHeader {
	private final static int PACKAGELENGTH_LEN = 2;
	private final static int PLAYERNAME_LEN = 0;
	private final static int PACKAGEID_LEN = 1;
	public final static int HEADER_LENGTH = PACKAGELENGTH_LEN + PLAYERNAME_LEN
			+ PACKAGEID_LEN;

	private int packageLength;
	private int packageID;


	public PackageHeader() {
		this(0, 0);
	}

	public PackageHeader(int packageLength, int packageID) {
		this.packageLength = packageLength;
		this.packageID = packageID;
	}

	public int getPackageLength() {
		return packageLength;
	}

	public int getPackageID() {
		return packageID;
	}

	public void clear() {
		packageLength = 0;
		packageID = 0;
	}

	// the first 2 bytes is ALWAYS packageLength
	private short decodePackageLength(byte[] arr) {
		short res = 0;
		res |= (int) arr[0] << 7; // byte "length" (8-1 cuz +-127)
		res |= (int) arr[1];
		return res;
	}

	// the first 2 bytes is ALWAYS packageLength
	private byte[] encodePackageLength(short len) {
		byte[] res = new byte[2];
		res[0] = (byte) (len >> 7);
		res[1] = (byte) (len & 127);
		return res;
	}

	private byte encodePackageID(short ID) {
		return (byte) ID;
	}

	private byte decodePackageID(byte[] ID) {
		// last item in the header is the package id
		return ID[HEADER_LENGTH - 1];
	}

	/**
	 * decoding all the information given by buf and saving the result in the
	 * instancevariable buf must contaion 3 elements, controll is done in the
	 * Server
	 */
	public void decodeHeader(byte[] buf) {
		packageLength = decodePackageLength(buf);
		packageID = decodePackageID(buf);
	}

	/**
	 * encoding all the information in the instancevariable
	 * 
	 * @return ByteBuffer
	 */
	public ByteBuffer encodeHeader() {
		ByteBuffer res = ByteBuffer.allocate(HEADER_LENGTH);
		res.put(encodePackageLength((short) packageLength));
		res.put(encodePackageID((short) packageID));
		res.position(0);
		return res;
	}

	public String toString() {
		return "PackageLength: " + packageLength + " PackageID: " + packageID;
	}
}
